#! /usr/local/bin/python
# -*- coding: utf-8 -*-

'''
酒吧、名人堂模块
'''

import random
import logging, traceback
from tornado.escape import json_encode,json_decode

import log
import util
from util import ConfigManager
import const
import mysqlHelper

import user
from user import UserManager

import bar_order
from bar_order import Room, BarOrderManager
import code_define
from store import *
from props_manager import *
import task
logger = logging.getLogger(__name__)

#------------------------------------------
#----Pk定时器处理
def _timerPKFunc(parms):
    '''参数: 房间对象, request'''
    if parms.__len__() != 2:
        log.print_warning(logger, "_timerPKFunc exec, parms.__len__() != 2 fail...")
        return
    
    tmpRoom, request = parms
    if tmpRoom is None or request is None:
        log.print_warning(logger, "_timerPKFunc exec, tmpRoom is None or request is None")
        return
    
    socket_id = request.socket_id
    
    #关闭定时器
    tmpRoom.stopTimerPK()
        
    tmpUserOther = tmpRoom.getUser_Other();             #原配
    if not tmpRoom.isStatePK() or tmpUserOther is None: #非PK状态，
        log.print_warning(logger, "_timerPKFunc exec, tmpRoom.isStatePK() is not, socket_id:[%s]" % socket_id)
        return
    
    #选择原配, 踢出PK者, 关闭定时器
    log.print_debug(logger, "_timerPKFunc exec, tmpRoom.isStatePK(), socket_id:[%s]" % socket_id)
    _bar_send_pk_result(request, tmpRoom, tmpUserOther.getUID())
    
   
#----续杯定时器处理
def _timerAddTimeFunc(parms):
    '''参数: tmpA, tmpB, 房间对象'''
    if len(parms) != 3:
        log.print_warning(logger, "_timerAddTimeFunc exec, parms.__len__() != 3 fail...")
        return
    
    tmpA, tmpB, tmpRoom = parms
    if tmpRoom is None or tmpA is None or tmpB is None:
        log.print_warning(logger, "_timerAddTimeFunc exec, tmpRoom is None or tmpA is None or tmpB is None")
        return
    
    tmpRoom.stopTimerAddTime()  #关闭定时器
    log.print_debug(logger, "_timerAddTimeFunc exec, room_id:[%s], RoomUsers:%s" % (tmpRoom.getRoomID(), tmpRoom.getRoomUserList()))
    tmpBarManager = BarOrderManager.instance()     #酒吧名人堂管理对象    
    
    #往双方发送续杯消息
    cmd = "bar_room_addtime"
    tmpSendMsgUtil = util.SendMsgUtil(None)         #消息发送器 
    
    #给A发送B的信息
    tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpB)   #B信息
    tmpSendMsgUtil.update_item("user", tmpItems)
    tmpSendMsgUtil.send(cmd, tmpA.getRequest())
    
    #给B发送A的信息
    tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpA)   #A信息
    tmpSendMsgUtil.update_item("user", tmpItems)
    tmpSendMsgUtil.send(cmd, tmpB.getRequest())
    
    #----开启等待续杯结果定时器
    tmpRoom.startTimerWaitAddTime(_timerWaitAddTimeFunc, tmpA, tmpB, tmpRoom)
         
    
    
#----等待续杯定时器处理
def _timerWaitAddTimeFunc(parms):
    '''参数: tmpA, tmpB, 房间对象'''
    if len(parms) != 3:
        log.print_warning(logger, "_timerWaitAddTimeFunc exec, parms.__len__() != 3 fail...")
        return
    
    tmpA, tmpB, tmpRoom = parms
    if tmpRoom is None or tmpA is None or tmpB is None:
        log.print_warning(logger, "_timerWaitAddTimeFunc exec, tmpRoom is None or tmpA is None or tmpB is None")
        return
    
    tmpRoom.stopTimerWaitAddTime()  #关闭定时器
    log.print_debug(logger, "_timerWaitAddTimeFunc exec, room_id:[%s], RoomUsers:%s" % (tmpRoom.getRoomID(), tmpRoom.getRoomUserList()))
    
    #结束聊天
    _deleteRoomProcess(tmpRoom, tmpA, tmpB, "addtime_fail")
    

#----处理新建立房间
def _newRoomProcess(tmpAskedUser, tmpOwnerUser, strIsAutoAsk="not"):
    '''参数: 主动者, 被搭讪者'''
    tmpBarManager = BarOrderManager.instance()     #酒吧名人堂管理对象    
    
    #两人非单身， 则建立房间失败
    if tmpAskedUser.getUserBarState() not in [0, -1] or tmpOwnerUser.getUserBarState() not in [0, -1]:
        return False
    
    #--建立约会房间----
    tmpRoom = tmpBarManager.addRoom(tmpAskedUser, tmpOwnerUser)
    if tmpRoom is None:
        return False
    
    log.print_debug(logger, "_newRoomProcess exec, room_id:[%s], RoomUsers:%s" % (tmpRoom.getRoomID(), tmpRoom.getRoomUserList()))
    
    #---判断两者是否带有 隐形符 道具, 有则给房间 防止打搅
    if PropManager.instance().isUsingPropsStealth(tmpAskedUser) or PropManager.instance().isUsingPropsStealth(tmpOwnerUser):
        tmpRoom.setStateNobother(2) #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
    
    tmpRandScene = random.randint(1, 100)   #随机场景,如果数值过大,客户端自己取模
    tmpRoom.setRoomScene(tmpRandScene)
    
    #--给AB发开始约会消息----
    cmd = "bar_room_begin"
    tmpSendMsgUtil3 = util.SendMsgUtil(None)                #消息发送器
    tmpSendMsgUtil3.add_item("scene", tmpRandScene)
    tmpSendMsgUtil3.add_item("add_time", const.Config_BarAddTime())#续杯时间
    tmpSendMsgUtil3.update_item("is_auto_ask", strIsAutoAsk)         #是否是自动匹配建立的房间
	
    #---发给A
    tmpItems = tmpBarManager.getUserInfoToClient(tmpOwnerUser)#被搭讪者B信息 
    tmpSendMsgUtil3.add_item("user", tmpItems)
    tmpSendMsgUtil3.update_item("is_ask", "yes")    #A是请求者搭讪者
    tmpSendMsgUtil3.send(cmd, tmpAskedUser.getRequest())      
    #---发给B
    tmpItems = tmpBarManager.getUserInfoToClient(tmpAskedUser)#请求搭讪者A信息
    tmpSendMsgUtil3.update_item("user", tmpItems)    
    tmpSendMsgUtil3.update_item("is_ask", "not")    #B不是请求搭讪者
    tmpSendMsgUtil3.send(cmd, tmpOwnerUser.getRequest())
    
    #push 状态变化
    tmpBarManager.pushUserBarState(tmpAskedUser) #push A的状态变化给所有"看见我的列表"的用户
    tmpBarManager.pushUserBarState(tmpOwnerUser) #push b的状态变化给所有"看见我的列表"的用户
    
    #----开启续杯定时器 
    tmpRoom.startTimerAddTime(_timerAddTimeFunc, True, tmpAskedUser, tmpOwnerUser, tmpRoom)
    #添加成功则执行任务
    task.taskManager.do_task(tmpAskedUser,'day_task','encounter',tmpOwnerUser.getUID())
    
    return True


#----处理删除房间(全部退出房间)
def _deleteRoomProcess(tmpRoom, tmpAskedUser, tmpOwnerUser, exitType, exitUID=0):
    '''参数: 房间对象，主动者, 被搭讪者'''
    log.print_debug(logger, "_deleteRoomProcess exec, room_id:[%s], RoomUsers:%s, exitType:[%s], exitUID:[%s]" 
                    % (tmpRoom.getRoomID(), tmpRoom.getRoomUserList(), exitType, exitUID))
       
    #---关闭所有定时器
    tmpRoom.stopAllTimer()
       
    #--消息体----
    cmd = "bar_room_finish"
    tmpSendMsgUtil3 = util.SendMsgUtil(None)        #消息发送器
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象
    
    #default: 普通约会结束;addtime_fail:续杯失败; force_exists:强制结束 ; offline:对方掉线或刷新退出           
    tmpSendMsgUtil3.add_item("type", exitType)  
    
    
    tmpGold_girl, tmpGold_boy = tmpRoom.getGoldByTalkTime() #根据聊天时间获得翻牌金币
    tmpExp = tmpRoom.getExpByTalkTime()                     #根据聊天时间获得的经验 
    
    tmpExitUser = tmpAskedUser          #强退者
    tmpNotExitUser = tmpOwnerUser       #非强退者
    bForceExit = False                  #强退或掉线状态
    
    tmpRandGold_Exit = tmpGold_girl     #请求退出者获得的金币
    if tmpExitUser.getSex() == 1:
        tmpRandGold_Exit = tmpGold_boy
    tmpRandGold_NotExit = tmpGold_girl  #非退出者获得的金币
    if tmpNotExitUser.getSex() == 1:
        tmpRandGold_NotExit = tmpGold_boy
    
    tmpExp_Exit = tmpExp                #请求退出者获得的经验
    tmpExp_NotExit = tmpExp             #非请求退出者获得的经验
    
    #---根据规则获取随机掉落礼包
    tmpGiftGoodsList_Exit, tmpGiftGoodsLevel_Exit, tmpBoolGetLevelGift_Exit = tmpBarManager.getBarRoomRandGiftGoodsList(tmpExitUser)
    tmpGiftGoodsList_NotExit, tmpGiftGoodsLevel_NotExit, tmpBoolGetLevelGift_NotExit = tmpBarManager.getBarRoomRandGiftGoodsList(tmpNotExitUser)
    
    if exitType in ("force_exists", "offline"):  #强退, 对方掉线或刷新退出
        bForceExit = True
        if exitUID == tmpOwnerUser.getUID():
            tmpExitUser = tmpOwnerUser
            tmpNotExitUser = tmpAskedUser
        #强退, 掉线或刷新退出,扣强出者数值
        util.CountUserUtil.judgeAndEditExt(cmd, tmpExitUser.getRequest(), tmpExitUser.getUID(), "BarRoom_bar_force_exists_room", False)

        tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpExitUser)   #强退/掉线者信息
        tmpSendMsgUtil3.update_item("user", tmpItems)
        tmpRandGold_Exit = 0  
        tmpExp_Exit = 0  
        tmpGiftGoodsList_Exit = []
    
    
    #---记录邂逅记录--1)邂逅数量加1--
    user.UserManager.updateLogTotalBarTalking()
        
    #---记录邂逅记录--2)插入邂逅记录-
    add_time = tmpRoom.m_addtime_info.m_addtime_state           #0:未续杯  1:已续杯 
    add_time_pay =  tmpRoom.m_addtime_info.m_pay_type           #支付方式
    s_time = util.getTimeSecondToStr(tmpRoom.getBeginTime())    #开始时间 
    e_time = util.getTimeSecondToStr(time.time())        		#结束时间
    sumtime = tmpRoom.getTimeInterval()                         #时间间隔
    user.UserManager.insertLogBarTalking(tmpExitUser, tmpNotExitUser, add_time, exitType, add_time_pay, s_time, e_time, sumtime)
   
    #---记录邂逅记录--3)续杯, 则续杯总数加一
    if tmpRoom.m_addtime_info.isAddtime(): 
        user.UserManager.updateLogTotalBarAddtime()
   
    
    #---从房间踢出两人
    tmpRoom.killUser(tmpAskedUser)
    tmpRoom.killUser(tmpOwnerUser)
    #---删除房间
    tmpBarManager.removeRoom(tmpRoom)
    
    #--两人获得的最终金币及经验
    tmpGoldTotal_Exit = tmpRandGold_Exit
    tmpExpTotal_Exit = tmpExp_Exit
    tmpGoldTotal_NotExit = tmpRandGold_NotExit
    tmpExpTotal_NotExit = tmpExp_NotExit
    
    #----有一方带了光环道具, 则经验， 金币按比例增加
    tmpConfigScale = const.Config_props_halo_add_exp()      #配置比例 
    tmpPropMagIns = PropManager.instance()
    if tmpPropMagIns.isUsingPropsHalo(tmpExitUser) or tmpPropMagIns.isUsingPropsHalo(tmpNotExitUser):
        tmpGoldTotal_Exit = util.getValByScale(tmpRandGold_Exit,tmpConfigScale)         #请求退出者获得的金币
        tmpExpTotal_Exit = util.getValByScale(tmpExp_Exit,tmpConfigScale)               #请求退出者获得的经验
        tmpGoldTotal_NotExit = util.getValByScale(tmpRandGold_NotExit,tmpConfigScale)   #非退出者获得的金币
        tmpExpTotal_NotExit = util.getValByScale(tmpExp_NotExit,tmpConfigScale)         #非请求退出者获得的经验
    
    #---双方有一方关注了， 则经验减半
    tmpUID = tmpNotExitUser.getUID()
    if tmpExitUser.isInMyAtttListUID(tmpUID) or tmpExitUser.isInAtttMeListUID(tmpUID):
        tmpScale = const.Config_Bar_end_exp_friend_scale()  #邂逅结束-双方有关注，得到的经验比例
        tmpExpTotal_Exit = int(tmpExpTotal_Exit * tmpScale / 100)
        tmpExpTotal_NotExit = int(tmpExpTotal_NotExit * tmpScale / 100)
    
    
    #---发给退出约会消息给两人
    tmpSendMsgUtil3.add_item("random", tmpRandGold_Exit)        #随机金币  
    tmpSendMsgUtil3.add_item("gold", tmpGoldTotal_Exit)         #获得的金币  
    tmpSendMsgUtil3.add_item("exp", tmpExpTotal_Exit)           #获得的经验
    tmpSendMsgUtil3.add_item("gift_goods_list", tmpGiftGoodsList_Exit)   #获得的赠送商品    
    tmpSendMsgUtil3.send(cmd, tmpExitUser.getRequest())       
      
    tmpSendMsgUtil3.add_item("random", tmpRandGold_NotExit)     #随机金币   
    tmpSendMsgUtil3.add_item("gold", tmpGoldTotal_NotExit)      #获得的金币  
    tmpSendMsgUtil3.add_item("exp", tmpExpTotal_NotExit)        #获得的经验
    tmpSendMsgUtil3.add_item("gift_goods_list", tmpGiftGoodsList_NotExit)   #获得的赠送商品
    tmpSendMsgUtil3.send(cmd, tmpNotExitUser.getRequest())
    
    
    if not bForceExit: #非强退或掉线状态， 给请求退出者增加数值
        #---计算数值变化-通知数值变化--    
        tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项
        ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, tmpGoldTotal_Exit)    #金币
        ConfigManager.setLogicInfoVal_Exp(tmpLogicMapObj, tmpExpTotal_Exit)      #经验
        ConfigManager.setLogicInfoVal_gift_goods_list(tmpLogicMapObj, tmpGiftGoodsList_Exit)      #翻牌礼包
        
        util.CountUserUtil.judgeAndEditExt(cmd, tmpExitUser.getRequest(), tmpExitUser.getUID(), tmpLogicMapObj, False)

    #---计算数值变化-通知数值变化--
    tmpLogicMapObj = ConfigManager.getLogicInfo("default_logic") #获取默认配置项
    ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, tmpGoldTotal_NotExit)     #金币
    ConfigManager.setLogicInfoVal_Exp(tmpLogicMapObj, tmpExpTotal_NotExit)       #经验
    ConfigManager.setLogicInfoVal_gift_goods_list(tmpLogicMapObj, tmpGiftGoodsList_NotExit)      #翻牌礼包
    util.CountUserUtil.judgeAndEditExt(cmd, tmpNotExitUser.getRequest(), tmpNotExitUser.getUID(), tmpLogicMapObj, False)

         
    #--互相加入对方的"我约会过的" 列表
    tmpAskedUser.insertUserIChatList(tmpOwnerUser.getUID())
    tmpOwnerUser.insertUserIChatList(tmpAskedUser.getUID())
        
    #push 状态变化
    tmpBarManager.pushUserBarState(tmpAskedUser) #push A的状态变化给所有"看见我的列表"的用户
    tmpBarManager.pushUserBarState(tmpOwnerUser) #push b的状态变化给所有"看见我的列表"的用户
    
    #---有增加等级礼包----
    if tmpBoolGetLevelGift_Exit == 1:  #当前获得的是否等级礼包, 0为非， 1为获得
        tmpExitUser.addGetGiftGoods(tmpGiftGoodsLevel_Exit, tmpGiftGoodsList_Exit)  #保存到缓存
        UserManager.saveUserRemarkInfoToDB(tmpExitUser)  #保存到DB
    if tmpBoolGetLevelGift_NotExit == 1:
        tmpNotExitUser.addGetGiftGoods(tmpGiftGoodsLevel_NotExit, tmpGiftGoodsList_NotExit)  #保存到缓存
        UserManager.saveUserRemarkInfoToDB(tmpNotExitUser)  #保存到DB
    
    if tmpRoom.m_addtime_info.m_addtime_state==1:
	    #添加成功则执行任务        
        task.taskManager.do_task(tmpAskedUser,'day_task','encounter_refill',tmpOwnerUser.getUID())        
        if tmpAskedUser.m_map_my_attt.get('%s'%tmpOwnerUser.getUID()):            
            task.taskManager.do_task(tmpAskedUser,'day_task','encounter_friend',tmpOwnerUser.getUID())
    return True 


#---处理PK结果, 并发消息
def _bar_send_pk_result(request, tmpRoom, tmpContiuneUID, bOnlySelect=False, killerName=None):
    '''bOnlySelect: 是否裁判选择'''
    socket_id = request.socket_id
    tmpCmd = "bar_pk_result"    
    
    #--关闭定时器    
    tmpRoom.stopTimerPK()
    
    tmpBarManager = BarOrderManager.instance()  #酒吧名人堂管理对象     
    tmpSendMsgUtil = util.SendMsgUtil(request)  #消息发送器
    
    usersDict = tmpRoom.getRoomUserObjMapExt()  #获取房间所有人信息,返回字典 '''    
    tmpUserOnly = usersDict["only"]             #裁判者 
    tmpUserOther = usersDict["other"]           #原配
    tmpUserPK = usersDict["pk"]                 #PK者
     
    exitUser = None     #退出者
    result_type = 2     #2:PK者退出, 3原配退出
    tmpStrConfigName = "BarRoom_bar_pk_result_lose"  #PK者插足结果数值名
    
    tmpA = tmpUserOnly
    tmpB = None
    bSelectPK = tmpRoom.isUserIsPK(tmpContiuneUID) #选择的是PK者
    if bSelectPK: #选择继续聊天的是PK者,#踢走原配     
        if bOnlySelect:  #裁判选择踢走原配 , 判断原配 是否使用防踢道具, 使用，则返回错误码, 否则踢走原配 者
            if PropManager.instance().isUsingPropsCheeky(tmpUserOther):   #---原配用户使用了"厚脸皮",
                tmpSendMsgUtil.update_res("targe_use_props_cheeky")  
                tmpSendMsgUtil.send()
                log.print_warning(logger, "_bar_send_pk_result exec, socket_id:[%s], fail, targeUser:[%s] otherUser, use_props_cheeky" % (socket_id, tmpUserPK.getUID()))
                return
        tmpStrConfigName = "BarRoom_bar_pk_result_win"  #PK者插足结果数值名
        tmpRoom.killUser(tmpUserOther)          #踢走原配        
        tmpUserOnly.setUserBarStateDouble()     #酒吧状态 1:普通约会
        tmpUserPK.setUserBarStateDouble()       #酒吧状态 1:普通约会
        result_type = 3                         #3原配退出
        exitUser = tmpUserOther
        tmpB = tmpUserPK        
        log.print_debug(logger, "_bar_send_pk_result exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], tmpContiuneUID:[%s] is pk" 
                    % (tmpRoom.getRoomID(), tmpRoom.getRoomUserList(), socket_id, tmpContiuneUID)) 
    else:#选择的是原配,#踢走PK者
        if bOnlySelect:  #裁判选择踢走PK者, 判断PK是否使用防踢道具, 使用，则返回错误码, 否则踢走PK者
            if PropManager.instance().isUsingPropsCheeky(tmpUserPK):   #---PK用户使用了"厚脸皮",
                tmpSendMsgUtil.update_res("targe_use_props_cheeky")  
                tmpSendMsgUtil.send()
                log.print_warning(logger, "_bar_send_pk_result exec, socket_id:[%s], fail, targeUser:[%s] PKUser, use_props_cheeky" % (socket_id, tmpUserPK.getUID()))
                return    
        tmpStrConfigName = "BarRoom_bar_pk_result_lose"  #PK者插足结果数值名        
        tmpRoom.killUser(tmpUserPK)             #踢走PK者        
        tmpUserOnly.setUserBarStateDouble()     #酒吧状态 1:普通约会
        tmpUserOther.setUserBarStateDouble()    #酒吧状态 1:普通约会
        result_type = 2                         #2:PK者退出
        exitUser = tmpUserPK
        tmpB = tmpUserOther
        log.print_debug(logger, "_bar_send_pk_result exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], tmpContiuneUID:[%s] is other" 
                    % (tmpRoom.getRoomID(), tmpRoom.getRoomUserList(), socket_id, tmpContiuneUID))
    #--修改房间状态
    tmpRoom.setStateDefault()
       
    #---判断两者是否带有 隐形符 道具, 有则给房间 防止打搅
    if PropManager.instance().isUsingPropsStealth(tmpA) or PropManager.instance().isUsingPropsStealth(tmpB):
        tmpRoom.setStateNobother(2) #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
    else:
        tmpRoom.setStateNobother(0)
        
    #---插足者数值变化    
    util.CountUserUtil.judgeAndEditExt(tmpCmd, tmpUserPK.getRequest(), tmpUserPK.getUID(), tmpStrConfigName, False)
        		
    #----续杯定时器----------
    #PK成功,则重新启动定时器; 
    #如果是原配和裁判,未续杯, 则按剩余时间开启定时器
    bNew = True
    bStartTimer = True
    if not tmpRoom.m_addtime_info.isNewUser(tmpA.getUID(), tmpB.getUID()): #原配和裁判
        bNew = False
        if tmpRoom.m_addtime_info.isAddtime(): #原配和裁判，已续杯,则返回, 不开启定时器
            bStartTimer = False
    if bStartTimer:
        tmpRoom.startTimerAddTime(_timerAddTimeFunc, bNew, tmpA, tmpB, tmpRoom)
		
    #--#消息发送器
    tmpSendMsgUtil.add_item("type", result_type)
    tmpSendMsgUtil.add_item("scene", tmpRoom.getRoomScene())                        #聊天场景
    tmpSendMsgUtil.add_item("add_time", tmpRoom.m_addtime_info.getRemainTime())     #多少秒后显示续杯面板)                      #续杯时间(秒)
    tmpItems = tmpBarManager.getUserInfoToClientSimple(exitUser)       #退出者信息
    tmpSendMsgUtil.add_item("user", tmpItems) 
    if killerName:
        tmpSendMsgUtil.add_item("killer", killerName)                   #踢人者 昵称
        
        
    #-系统通知三人此次插足PK的结果
    tmpMsg = tmpSendMsgUtil.getEncodeContent() #编码 
    tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUserOnly.getRequest(), msg=tmpMsg)
    tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUserOther.getRequest(), msg=tmpMsg)
    tmpSendMsgUtil.send(cmd=tmpCmd, request=tmpUserPK.getRequest(), msg=tmpMsg) 
 
    #给房间三人的 "看见我的列表" 发送状态改变消息
    tmpBarManager.pushUserBarState(tmpUserOnly)    #push 裁判的状态变化给所有"看见我的列表"的用户
    tmpBarManager.pushUserBarState(tmpUserOther)   #push 原配的状态变化给所有"看见我的列表"的用户
    tmpBarManager.pushUserBarState(tmpUserPK)      #push PK者的状态变化给所有"看见我的列表"的用户

    #----记录pk信息------------
    user.UserManager.updateLogTotalBarPK() #总数加一
    if bSelectPK: #pk成功
        user.UserManager.updateLogTotalBarPKSuccess() #插足成功总数加一
        user.UserManager.updateUserCount('count_pk_success', 1, tmpContiuneUID)      #增加: 我插足成功的数量
		
        #---pk成功,即踢走原配, 结束原配跟裁判的邂逅, 插入邂逅记录-
        add_time = tmpRoom.m_addtime_info.m_addtime_state           #0:未续杯  1:已续杯 
        add_time_pay =  tmpRoom.m_addtime_info.m_pay_type           #支付方式
        s_time = util.getTimeSecondToStr(tmpRoom.getBeginTime())    #开始时间 
        e_time = util.getTimeSecondToStr(time.time())        		#结束时间
        sumtime = tmpRoom.getTimeInterval()                         #时间间隔
        exitType = "pked_lose"                                      #邂逅结束方式
        user.UserManager.insertLogBarTalking(tmpUserOnly, tmpUserOther, add_time, exitType, add_time_pay, s_time, e_time, sumtime)
		
        #添加成功则执行任务
        task.taskManager.do_task(tmpUserPK,'day_task','pk_success',tmpUserOther.getUID())

#------------------------------------------            
#------#进入酒吧--
def method_enter_bar(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_enter_bar exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "enter_bar"
        
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
     
    tmpBarManager = BarOrderManager.instance()       #酒吧管理器
    
    tmpBarManager.enter(tmpOwnerUser)                          #进入酒吧
    tmpTSize = tmpBarManager.get_T_size(tmpOwnerUser);         #T台排队人数
    tmpMyTOrder = tmpBarManager.get_T_user_order(tmpOwnerUser) #我在T台的排名
    
    #发送消息---
    tmpSendMsgUtil = util.SendMsgUtil(request)
    tmpSendMsgUtil.add_item("count", tmpTSize)      #T台排队人数
    tmpSendMsgUtil.add_item("await", tmpMyTOrder)   #我在T台的排名
    tmpSendMsgUtil.add_item("single_total", tmpBarManager.getTotalSingleCount())  #单身总数
    tmpSendMsgUtil.add_item("double_total", tmpBarManager.getTotalDoubleCount())  #房间总数 
    tmpSendMsgUtil.send(cmd)
    
    #--发送T台信息给用户
    tmpBarManager.pushTListToSomebody(tmpOwnerUser)


#------#离开酒吧--
def method_leave_bar(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_leave_bar exec, socket_id:[%s], data:%s" % (socket_id, data))  
    cmd = "leave_bar"
    
    tmpBarManager = BarOrderManager.instance()   #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return 
    
    tmpBarManager.leaveBarOrder(request, tmpOwnerUser)   #处理离开酒吧/名人堂或者用户掉线
    
    #发送消息---
    tmpSendMsgUtil.send(cmd)


#------#获取单身/聊天中列表--
def method_get_bar_list(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_get_bar_list exec, socket_id:[%s], data:%s" % (socket_id, data))     
    cmd = "get_bar_list"

    data_dict = json_decode(data)
    tmpReqSingle = data_dict.get('single')  #请求单身者数量
    tmpReqDouble = data_dict.get('double')  #请求约会者数量
        
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
   
    ownerUID = tmpOwnerUser.getUID()  #我的UID
    
    tmpSingleMax = const.Config_GetBarSingleMaxCount() #限定请求长度
    tmpDoubleMax = const.Config_GetBarDoubleMaxCount() #限定请求长度
    
    #限定请求的数量
    #if tmpReqSingle < 0 or tmpReqSingle > tmpSingleMax or tmpReqDouble < 0 or tmpReqDouble > tmpDoubleMax:
    if tmpReqSingle not in range(1, tmpSingleMax) or tmpReqDouble not in range(1, tmpDoubleMax):
        log.print_warning(logger, "method_get_bar_list exec, request range error, 0<default_single<%s, req_single:%s; 0<default_double<%s, req_double:%s" % 
                          (tmpSingleMax, tmpReqSingle, tmpDoubleMax, tmpReqDouble))
        tmpSendMsgUtil.update_res("bad_request")   
        tmpSendMsgUtil.send(cmd) 
        return
                            
    #异性单身列表        
#    tempSingleInfo = []    
#    tempListSingl = tmpBarManager.getSingleUserList(tmpOwnerUser.getDiffentSex())
#    tempList = util.getRandomFromList(tempListSingl, tmpReqSingle)  #随机获取单身队列
#    for v in tempList:
#        tmpUser = UserManager.get_user_by_uid(v)
#        if tmpUser is None:
#            continue
#        tmpItems = tmpBarManager.getUserInfoToClientExt(tmpUser) #获取用户信息
#        tempSingleInfo.append(tmpItems)
#        
#        tmpUser.insertBarSeeMeList(ownerUID)             #--把 我的uid加入到对方的“看见我的人队列"       
#        tmpOwnerUser.insertBarISeeList(tmpUser.getUID()) #--把对方的uid加入到我的“我看见的人队列"   
        
    #---获取单身异性对象, (优先获取同省的单身异性), 且对方加入"我看见的队列" 和  我加入对方“看见我的队列"
    tempSingleInfo = tmpBarManager.getSingleUserListExt(tmpOwnerUser, tmpReqSingle)        
    
    #房间列表
    tempDoubleInfo = []
    tempMapDouble = tmpBarManager.getDoubleUserMap()            #获取普通约会的房间(普通约会，无pk 无隐身符， 无防打搅牌的房间)
    tempList = util.getKeysFromMap(tempMapDouble, tmpReqDouble) #随机获取约会房间keys队列
    #--获取房间双人信息
    for room_id in tempList:
        room = tempMapDouble.get(room_id)
        if room is None:
            continue
            
        tmpRoomObj = {}
        tmpRoomObj["room_id"] = room_id   
        tmpRoomObj["info"] = []
        
        tmpRoomObj["room_state"] = room.getRoomState()              #约会房间状态 0:普通约会  1:PK中
        tmpRoomObj["state_nobother"] = room.getRoomStateNobother()  #房间打搅状态   #0: 默认, 1:使用了防打扰牌道具, 2:使用了隐形符
        tmpRoomObj["state_addtime"] = room.m_addtime_info.getAddTimeState() #房间续杯状态, 0:未续杯  1:已续杯
        tmpRoomObj["uid_pk"] = room.getPKUID()   #房间PK状态, 返回小三UID, 否则为0
         
        for uid in room.m_list_user:
            user = UserManager.get_user_by_uid(uid)
            if user is None:
                continue            
            tmpItems = tmpBarManager.getUserInfoToClientSimple(user)#获取用户信息
            tmpRoomObj["info"].append(tmpItems)
            
            user.insertBarSeeMeList(ownerUID)             #--把 我的uid加入到对方的“看见我的人队列"       
            tmpOwnerUser.insertBarISeeList(user.getUID()) #--把对方的uid加入到我的“我看见的人队列" 

        tempDoubleInfo.append(tmpRoomObj)
    
    #添加列表信息到发送字典
    tmpSendMsgUtil.add_item("single_total", tmpBarManager.getTotalSingleCount())  #单身总数
    tmpSendMsgUtil.add_item("double_total", tmpBarManager.getTotalDoubleCount())  #房间总数 
    tmpSendMsgUtil.add_item("single", tempSingleInfo)
    tmpSendMsgUtil.add_item("double", tempDoubleInfo)
    
    #发送消息---
    tmpSendMsgUtil.send(cmd)

#-----#用户A请求搭讪B---
def method_ask_talking(request, data): 
    socket_id = request.socket_id
    log.print_debug(logger, "method_ask_talking exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "ask_talking"
    
    data_dict = json_decode(data)
    tmpUID = data_dict.get('uid')
    
    tmpClientAdditon = data_dict.get('client_addition')#客户端附加信息
    if not tmpClientAdditon:
        tmpClientAdditon = ""
    
    tmpBarManager = BarOrderManager.instance() #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)  #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    if tmpUID in const.Config_Bar_Default_users:   #给客户端帮助使用
        tmpSendMsgUtil.add_item("client_addition", tmpClientAdditon) #客户端附加信息
        tmpSendMsgUtil.send(cmd)
        return;
    
    if tmpUID == tmpOwnerUser.getUID(): #不能请求跟自己聊天
        log.print_warning(logger, "method_ask_talking exec, socket_id:[%s], faile: tmpUID == tmpOwnerUser.getUID()" % socket_id) 
        tmpSendMsgUtil.update_res("user_is_myself")        
        tmpSendMsgUtil.send(cmd)
        return   
    
    tmpAskedUser = UserManager.get_user_by_uid(tmpUID)
    if tmpAskedUser is None: #被请求者B不在线
        log.print_warning(logger, "method_ask_talking exec, socket_id:[%s], faile: asked User:[%s] is null" % (socket_id, tmpUID)) 
        tmpSendMsgUtil.update_res("user_is_null")        
        tmpSendMsgUtil.send(cmd)
        return    

    if tmpAskedUser.getSex() == tmpOwnerUser.getSex(): #不能跟同性别的聊天
        log.print_warning(logger, "method_ask_talking exec, socket_id:[%s], faile:  user_sex_same" % socket_id) 
        tmpSendMsgUtil.update_res("user_sex_same")
        tmpSendMsgUtil.send(cmd)
        return    
     
    if tmpAskedUser.getUserBarState() not in [0, -1]: #该用户不是单身
        log.print_warning(logger, "method_ask_talking exec, socket_id:[%s], faile: user_is_busy" % socket_id) 
        tmpSendMsgUtil.update_res("user_is_busy")
        tmpSendMsgUtil.send(cmd)
        return
   
    #----------数值计算, 数值不够，则发错误消息,返回
    #----------数值计算, 数值够, 扣数值， 并push数值变化 
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), "BarRoom_ask_talking"):
        return  #数值扣除不成功, 则返回
    
    tmpAskedUser.insertBarAskIRecvList(tmpOwnerUser.getUID())#把 请求者加入到被搭讪方"向我搭讪"列表    
    tmpOwnerUser.insertBarAskISendList(tmpAskedUser.getUID())#把被搭讪方加入我的"我发出搭讪列表"
    
    #系统往对方发请求通知
    tmpSendMsgUtil2 = util.SendMsgUtil(tmpAskedUser.getRequest())  #消息发送器
    tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpOwnerUser)
    tmpItems['my_bodyinfo']=tmpOwnerUser.getMyBodyInfo()
    tmpSendMsgUtil2.add_item("user", tmpItems)      #请求者信息   
    tmpSendMsgUtil2.add_item("client_addition", tmpClientAdditon) #客户端附加信息
    tmpSendMsgUtil2.send(cmd)
     
    #发送响应消息---    
    tmpSendMsgUtil.add_item("client_addition", tmpClientAdditon) #客户端附加信息
    tmpSendMsgUtil.send(cmd)


#------B同意或者拒绝搭讪请求--
def method_answer_talking(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_answer_talking exec, socket_id:[%s], data:%s" % (socket_id, data))
    cmd = "answer_talking"
    
    data_dict = json_decode(data)
    tmpUID = data_dict.get('uid')    #请求搭讪者A
    tmpType = data_dict.get('type')  #0:拒绝 1:同意
    
    tmpBarManager = BarOrderManager.instance()     #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    #请求者A是否在我的”向我搭讪列表" 或 是否在线
    tmpAskedUser = UserManager.get_user_by_uid(tmpUID)
    if tmpAskedUser is None or not tmpOwnerUser.isInBarAskIRecvList(tmpUID): 
        log.print_warning(logger, "method_answer_talking exec, socket_id:[%s], User:[%s] is null or not ask to me" % (socket_id, tmpUID)) 
        tmpSendMsgUtil.update_res("user_is_null")        
        tmpSendMsgUtil.send(cmd)
        tmpOwnerUser.delBarAskIRecvList(tmpUID)#把请求者从被搭讪方的“向我搭讪列表"删除
        return
        
    tmpOwnerUser.delBarAskIRecvList(tmpUID)#把请求者从被搭讪方的“向我搭讪列表"删除

    #判断用户是否单身
    if tmpAskedUser.getUserBarState() not in [0, -1] or tmpOwnerUser.getUserBarState() not in [0, -1]: 
        log.print_warning(logger, "method_ask_talking exec, socket_id:[%s], faile: user_is_busy" % socket_id) 
        tmpSendMsgUtil.update_res("user_is_busy")
        tmpSendMsgUtil.send(cmd)
        return
    
    #系统往A发答复消息    
    tmpSendMsgUtil2 = util.SendMsgUtil(tmpAskedUser.getRequest())  #消息发送器
    tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpOwnerUser)
    tmpSendMsgUtil2.add_item("type", tmpType)   #B的答复结果
    tmpSendMsgUtil2.add_item("user", tmpItems)  #被搭讪者B信息
    tmpSendMsgUtil2.send(cmd)
    
    if tmpType == 1: # 1:同意
        if not _newRoomProcess(tmpAskedUser, tmpOwnerUser): #新房间处理
            log.print_warning(logger, "method_answer_talking exec, room_create_fail, socket_id:[%s]" % socket_id)
            tmpSendMsgUtil.update_res("room_create_fail")        
            tmpSendMsgUtil.send(cmd)
    else:
        #发送拒绝消息--
        tmpSendMsgUtil.send(cmd) 


#-----#发聊天信息---
def method_send_talking_info(request, data): 
    socket_id = request.socket_id
    cmd = "send_talking_info"

    data_dict = json_decode(data)
    tmpContent = data_dict.get('content')    #内容

    tmpBarManager = BarOrderManager.instance()     #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    room_id = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, room_id)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return

    log.print_debug(logger, "method_send_talking_info exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (room_id, tmpRoom.getRoomUserList(), socket_id, data))
    
    tmpSendMsgUtil.add_item("content", tmpContent)
    tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpOwnerUser)   #发消息者用户信息
    tmpSendMsgUtil.add_item("user", tmpItems)
    tmpUserType = tmpRoom.getTalkingUserType(tmpOwnerUser)      #获取聊天者类型(pk, only, other)
    tmpSendMsgUtil.add_item("user_type", tmpUserType)
    
    tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)  #给房间所有人发消息

    
#-----#发动作信息---
def method_send_action(request, data): 
    socket_id = request.socket_id
    cmd = "send_action"

    data_dict = json_decode(data)
    tmpAction = data_dict.get('action')    #动作
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return

    room_id = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, room_id)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    log.print_debug(logger, "method_send_action exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (room_id, tmpRoom.getRoomUserList(), socket_id, data))
    
    #----------数值计算, 数值不够，则发错误消息,返回
    #----------数值计算, 数值够, 扣数值， 并push数值变化 
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), "BarRoom_send_action"):
        return  #数值扣除不成功, 则返回
    
    tmpSendMsgUtil.add_item("action", tmpAction)
    tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpOwnerUser)   #发消息者用户信息
    tmpSendMsgUtil.add_item("user", tmpItems)
    tmpUserType = tmpRoom.getTalkingUserType(tmpOwnerUser)      #获取聊天者类型(pk, only, other)
    tmpSendMsgUtil.add_item("user_type", tmpUserType)
    
    tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)  #给房间所有人发消息

    
#-----#点歌---
def method_send_music(request, data): 
    socket_id = request.socket_id
    cmd = "send_music"

    data_dict = json_decode(data)
    tmpMusicID = data_dict.get('music')             #歌曲ID
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    room_id = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, room_id)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    log.print_debug(logger, "method_send_music exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (room_id, tmpRoom.getRoomUserList(), socket_id, data)) 
    
    
    #从商场商品列表获取商品信息 ---
    tmpMusicObj = store.getGoodsInfoExt(cmd, request, tmpMusicID)
    if tmpMusicObj is None: #商品ID不存在， 发错误消息， 退出
        return
    tmpMusicName = tmpMusicObj.get("golds_name")
    tmpMusicGold = tmpMusicObj.get("gold")
    tmpMusicMoney = tmpMusicObj.get("money")
    
    #----------数值计算, 数值不够，则发错误消息,返回
    #----------数值计算, 数值够, 扣数值， 并push数值变化  
    tmpLogicMapObj = ConfigManager.getLogicInfo("BarRoom_send_music") #获取配置项
    ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, tmpMusicGold, bNegative=True) #bNegative=True设置为负数
    ConfigManager.setLogicInfoVal_Money(tmpLogicMapObj, tmpMusicMoney, bNegative=True)  
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), tmpLogicMapObj):
        return  #数值扣除不成功, 则返回
    
    #----给被点歌者增减数值
    tmpAnotherUser = tmpRoom.getAnotherUser(tmpOwnerUser)
    if tmpAnotherUser:
        util.CountUserUtil.judgeAndEditExt(cmd, tmpAnotherUser.getRequest(), tmpAnotherUser.getUID(), "BarRoom_send_music_recv", False)
  
    tmpMusicInfo = {}
    tmpMusicInfo["id"] = tmpMusicID               #歌曲ID
    tmpMusicInfo["name"] = tmpMusicName           #歌曲名称
    tmpSendMsgUtil.add_item("music", tmpMusicInfo)
    
    tmpItems = tmpBarManager.getUserInfoToClientSimple(tmpOwnerUser)   #发消息者用户信息
    tmpSendMsgUtil.add_item("user", tmpItems)
    tmpUserType = tmpRoom.getTalkingUserType(tmpOwnerUser)      #获取聊天者类型(pk, only, other)
    tmpSendMsgUtil.add_item("user_type", tmpUserType)
    
    tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)  #给房间所有人发消息

    
#-----#准入PK-获取房间原配信息--
def method_bar_pk_before(request, data):
    socket_id = request.socket_id
    cmd = "bar_pk_before"

    data_dict = json_decode(data)
    tmpRoomID = data_dict.get('room_id')        #房间ID
    
    tmpBarManager = BarOrderManager.instance()     #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)     #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
        
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    log.print_debug(logger, "method_bar_pk_before exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    #人数不等于2 或 房间状态不是普通聊天，则房间不允许进入
    tmpRoomUserList = tmpRoom.getRoomUserObjList()
    if len(tmpRoomUserList) != 2 or tmpRoom.isStatePK() or not tmpRoom.isAdmitPK(): 
        log.print_warning(logger, "method_bar_pk_before exec, fail, room:[%s] is busy, sockID:[%s]" 
                          % (tmpRoomID, socket_id)) 
        tmpSendMsgUtil.update_res("room_is_busy")   
        tmpSendMsgUtil.send(cmd)
        return
    
    #或房间不能为打搅，则房间不允许进入
    if tmpRoom.isStateNobother(): 
        log.print_warning(logger, "method_bar_pk_before exec, fail, room:[%s] is busy, sockID:[%s]" 
                          % (tmpRoomID, socket_id)) 
        tmpSendMsgUtil.update_res("room_is_busy_nobother")   
        tmpSendMsgUtil.send(cmd)
        return
    
    #----------数值计算, 数值不够，则发错误消息,退出;数值够, 扣数值， 并push数值变化(扣勇气)
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), "BarRoom_bar_pk_before"):
        return  #数值扣除不成功, 则返回
    
    
    #----获取房间原配信息
    tmpA, tmpB = tmpRoomUserList
    
    tmpOther = tmpA
    if tmpB.getSex() == tmpOwnerUser.getSex(): #原配是和Pk同性别的玩家
        print "@@@@@>tmpItems@>", tmpB.getSex(), tmpOwnerUser.getSex()
        tmpOther =tmpB
    else:
        print "@@@@@>else:tmpItems@>", tmpB.getSex(), tmpOwnerUser.getSex()
    
    tmpItems = tmpBarManager.getUserInfoToClient(tmpOther)
    print "@@@@@@tmpItems@>", tmpItems

    shengmingList = []
    tizhibeishu = const.Config_PK_Constitution_Multiple()  #体质倍数
    levelbeishu = const.Config_PK_Level_Multiple()  #人物等级倍数

    tmpOwnerUser_shengming = tmpOwnerUser.getConstitution()*tizhibeishu + tmpOwnerUser.getLevel()*levelbeishu
    tmpItems_shengming = tmpItems['constitution']*tizhibeishu + tmpItems['level']*levelbeishu    
    shengmingList.append({'uid':tmpOwnerUser.getUID(), 'shengming':tmpOwnerUser_shengming})
    shengmingList.append({'uid':tmpItems['uid'], 'shengming':tmpItems_shengming})

    print "@@@@@-method_bar_pk_before-shengmingList>", shengmingList

    tmpSendMsgUtil.add_item("user", tmpItems) #给请求pk发送原配用户信息
    tmpSendMsgUtil.add_item("shengming", shengmingList) #给请求pk发送原配用户信息
    tmpSendMsgUtil.send(cmd)
   
#-----#准入pk---
def method_bar_pk(request, data):
    socket_id = request.socket_id
    cmd = "bar_pk"

    data_dict = json_decode(data)
    tmpRoomID = data_dict.get('room_id')        #房间ID
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
        
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return

    log.print_debug(logger, "method_bar_pk exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    #人数不等于2 或 房间状态不是普通聊天，或房间不能为打搅，则房间不允许进入"
    tmpRoomUserList = tmpRoom.getRoomUserObjList()
    if len(tmpRoomUserList) != 2 or tmpRoom.isStatePK() or tmpRoom.isStateNobother() or not tmpRoom.isAdmitPK(): 
        tmpSendMsgUtil.update_res("room_is_busy")   
        tmpSendMsgUtil.send(cmd)
        log.print_warning(logger, "method_bar_pk exec, fail, room:[%s] is busy, sockID:[%s]" % (tmpRoomID, socket_id))  
        return
    
    tmpA, tmpB = tmpRoomUserList    #房间两人信息    
    tmpOther = tmpA  #原配
    if tmpB.getSex() == tmpOwnerUser.getSex(): #原配是和Pk同性别的玩家
        tmpOther =tmpB
        
    #----比较pk者和原配的数据
    onlinePkResult = Room.getPKResult(tmpOwnerUser.getUID(), tmpOther.getUID(), 1)
    winUID = onlinePkResult[-1]['winUID']
    if winUID==tmpOwnerUser.getUID():
        tmpWinner = tmpOwnerUser
    else:
        tmpWinner = tmpOther        
    if tmpWinner is tmpOther:  #PK者准入PK失败
        strResult = "lose"
        strConfigName = "BarRoom_bar_pk_before_lose" 
    else: #准入pk胜利
        strResult = "win"
        strConfigName = "BarRoom_bar_pk_before_win"

    #---数值变化 , 数值不够, 则返回   
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), strConfigName):
        return
    
    log.print_debug(logger, "method_bar_pk exec, pk result:[%s], room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                 % (strResult, tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))

    #---发送回应消息
    tmpSendMsgUtil.add_item("result", strResult)                #pk结果
    #tmpSendMsgUtil.add_item('is_win', strResult)
    tmpSendMsgUtil.add_item('huihe', onlinePkResult)        #发送回合详细信息
    tmpSendMsgUtil.add_item("scene", tmpRoom.getRoomScene())    #聊天场景
    tmpSendMsgUtil.send(cmd)
    
    
    if tmpWinner is tmpOther:  #PK者准入PK失败
        return
    
    tmpPKTime = const.Config_BarPKLimitTime()    #酒吧约会房间 PK时间(默认限制 60秒)
    
    #发送房间两人信息给PK者---    
    tmpSendMsgUtil.add_item("pk_time", tmpPKTime)               #PK倒计时
    tmpSendMsgUtil.add_item("uid_pk", tmpOwnerUser.getUID())    #pk者ID
    tempRoomInfo = []    
    tmpItems = tmpBarManager.getUserInfoToClient(tmpA)
    tempRoomInfo.append(tmpItems)
    tmpItems = tmpBarManager.getUserInfoToClient(tmpB)
    tempRoomInfo.append(tmpItems)
    tmpSendMsgUtil.add_item("room", tempRoomInfo)
    tmpSendMsgUtil.send(cmd)
        
    #给房间原来两人发送PK者信息
    tmpSendMsgUtil2 = util.SendMsgUtil(request)  #消息发送器    
    tmpSendMsgUtil2.add_item("pk_time", tmpPKTime)              #PK倒计时
    tmpSendMsgUtil2.add_item("uid_pk", tmpOwnerUser.getUID())   #pk者ID
    tempRoomInfo = [] 
    tmpItems = tmpBarManager.getUserInfoToClient(tmpOwnerUser)
    tempRoomInfo.append(tmpItems)
    tmpSendMsgUtil2.add_item("room", tempRoomInfo)  
    tmpRoom.sendMsgToAllExt(cmd, tmpSendMsgUtil2, tmpOwnerUser.getUID())  #给房间其它人发消息
    
    #PK者加入房间,修改房间状态为PK状态
    tmpRoom.enterPK(tmpOwnerUser)   #把PK者加入房间,
    tmpRoom.setStatePK()            #修改房间状态
    
    tmpA.setUserBarStatePK()        #酒吧状态 2:约会PK中
    tmpB.setUserBarStatePK()        #酒吧状态 2:约会PK中
    
    #给房间三人的 "看见我的列表" 发送状态改变消息
    tmpBarManager.pushUserBarState(tmpA) #push 用户的状态变化给所有"看见我的列表"的用户
    tmpBarManager.pushUserBarState(tmpB) #push 用户的状态变化给所有"看见我的列表"的用户
    tmpBarManager.pushUserBarState(tmpOwnerUser) #push 用户的状态变化给所有"看见我的列表"的用户
    
    #开启PK定时器(到时间自动选择PK者)
    #tmpRoom.startTimerPK(_timerPKFunc, tmpRoom, request)
    
    #关闭续杯定时器, 计算并保存剩余时间
    tmpRoom.stopTimerAddTime()


def method_bar_pk_show(request, data):
    '''准入PK, 通知开始显示第三者形象'''
    socket_id = request.socket_id
    cmd = "bar_pk_show"
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
        
    tmpRoomID = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    log.print_debug(logger, "method_bar_pk_show exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    #给房间所有人发消息
    tmpPKTime = tmpRoom.getTimerPKLimitTime()    #PK倒计时剩余时间
    tmpSendMsgUtil.add_item("pk_time", tmpPKTime)  
    tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)
    

#-----#裁判同意某人插足---
def method_bar_pk_select_user(request, data): 
    socket_id = request.socket_id
    cmd = "bar_pk_select_user"

    data_dict = json_decode(data)
    tmpContiuneUID = data_dict.get('uid')           #可以继续聊天的用户ID 
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
        
    tmpRoomID = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
         
    log.print_debug(logger, "method_bar_pk_select_user exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    if not tmpRoom.isUserInRoom(tmpContiuneUID) or tmpRoom.m_state != 1:  
        log.print_warning(logger, "method_bar_pk_select_user exec,  fail, room_id:[%s] is not pk state, sockID:%s" 
                          % (tmpRoomID, socket_id))
        tmpSendMsgUtil.update_res("room_is_not_pk") #用户不在房间列表或房间不在PK状态  
        tmpSendMsgUtil.send(cmd)
        return
       
    _bar_send_pk_result(request, tmpRoom, tmpContiuneUID, True) #处理插足结果


#-----#请求自动匹配---
def method_ask_auto_talking(request, data): 
    socket_id = request.socket_id
    log.print_debug(logger, "method_ask_auto_talking exec, socket_id:[%s], data:%s" % (socket_id, data))
    cmd = "ask_auto_talking"

    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    #----------数值计算, 数值不够，则发错误消息,返回
    #----------数值计算, 数值够, 扣数值， 并push数值变化 
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpOwnerUser.getUID(), "BarRoom_ask_auto_talking"):
        return  #数值扣除不成功, 则返回
    
    tmpOtherUser = tmpBarManager.getAutoUser(tmpOwnerUser) #从自动等待邂逅队列获取一个异性
    if tmpOtherUser:
        if _newRoomProcess(tmpOtherUser, tmpOwnerUser, strIsAutoAsk="yes"): #新房间处理
            return
    
    #获取失败, 或新建立房间失败, 则把自己加入自动等待邂逅队列
    tmpBarManager.insertBarAutoList(tmpOwnerUser)
        
    #发送响应消息---
    tmpSendMsgUtil.send(cmd)
    
#-----#请求取消自动匹配---
def method_ask_cancel_auto_talking(request, data): 
    socket_id = request.socket_id
    log.print_debug(logger, "method_ask_cancel_auto_talking exec, socket_id:[%s], data:%s" % (socket_id, data))
    cmd = "ask_cancel_auto_talking"

    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    tmpBarManager.delFromAutoList(tmpOwnerUser)      #从自动等待邂逅队列删除
        
    #发送响应消息---
    tmpSendMsgUtil.send(cmd)
    
    
#-----#请求退出约会---
def method_bar_ask_exist_room(request, data):  
    socket_id = request.socket_id
    cmd = "bar_ask_exist_room"
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return 
        
    tmpRoomID = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    log.print_debug(logger, "method_bar_ask_exist_room exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    ownerUID = tmpOwnerUser.getUID()
    tmpItem = tmpBarManager.getUserInfoToClientSimpleExt(tmpOwnerUser)     #获取用户信息 
    tmpSendMsgUtil.add_item("user", tmpItem)
    
    if not tmpRoom.isStatePK(): #非PK状态，发退出请求给对方
        log.print_debug(logger, "method_bar_ask_exist_room exec, room:[%s] State is not PKState, socket_id:[%s] "
                     % (tmpRoomID, socket_id))
        tmpRoom.sendMsgToAllExt(cmd, tmpSendMsgUtil, ownerUID)
        return        
    else: #Pk状态...
        usersDict = tmpRoom.getRoomUserObjMapExt()  #获取房间所有人信息,返回字典 '''    
        tmpUserOnly = usersDict["only"]             #裁判者 
        tmpUserOther = usersDict["other"]           #原配
        tmpUserPK = usersDict["pk"]                 #PK者
        
        if ownerUID == tmpUserOnly.getUID():#请求者是裁判  #不允许裁判退出
            log.print_debug(logger, "method_bar_ask_exist_room exec, room:[%s] State is PKState, askUser is onlyUser, room_not_admit_exit, socket_id:[%s] "
                     % (tmpRoomID, socket_id))
            tmpSendMsgUtil.update_res("room_not_admit_exit")
            tmpSendMsgUtil.send(cmd)
            return
        elif ownerUID == tmpUserPK.getUID():#请求者是PK者#可假定为选择原配继续聊天, PK者直接退出房间
            log.print_debug(logger, "method_bar_ask_exist_room exec, room:[%s] State is PKState, askUser is pkUser, socket_id:[%s] "
                     % (tmpRoomID, socket_id))
            _bar_send_pk_result(request, tmpRoom, tmpUserOther.getUID())
            return
        else: #请求者是原配, 发退出请求给裁判    
            log.print_debug(logger, "method_bar_ask_exist_room exec, room:[%s] State is PKState, askUser is otherUser, socket_id:[%s] "
                     % (tmpRoomID, socket_id))        
            tmpRoom.sendMsgToOne(cmd, tmpSendMsgUtil, tmpUserOnly)


#-----#答复退出约会请求---
def method_bar_answer_exists_room(request, data):  
    socket_id = request.socket_id
    cmd = "bar_answer_exists_room"
    
    data_dict = json_decode(data)
    tmpAskUID = data_dict.get('uid')                  #原配用户ID 
    tmpAnswer = data_dict.get('type')                 #0:拒绝 1:同意     

    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return 
        
    tmpRoomID = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
     
    log.print_debug(logger, "method_bar_answer_exists_room exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    tmpOtherUser = UserManager.get_user_by_uid(tmpAskUID)
    if tmpOtherUser is None: #原配不在线
        tmpSendMsgUtil.update_res("user_is_null")        
        tmpSendMsgUtil.send(cmd)
        log.print_warning(logger, "method_bar_answer_exists_room exec, socket_id:%s, User[%s] is null" % (socket_id, tmpAskUID)) 
        return
    
    tmpSendMsgUtil.add_item("uid", tmpAskUID)
    tmpSendMsgUtil.add_item("type", tmpAnswer)
    tmpRoom.sendMsgToOne(cmd, tmpSendMsgUtil, tmpOtherUser) #把响应发给对方
        
    if tmpAnswer == 1:  #1:同意
        if tmpRoom.isStatePK(): #同意, PK状态,则原配退出房间,PK者成功PK
            _bar_send_pk_result(request, tmpRoom, tmpRoom.getPKUID())        
        else: #同意, 普通聊天状态，则双方退出房间
            _deleteRoomProcess(tmpRoom, tmpOwnerUser, tmpOtherUser, "default")
    
    
#-----#强退出约会---
def method_bar_force_exists_room(request, data):  
    socket_id = request.socket_id
    cmd = "bar_force_exists_room"

    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return 
        
    tmpRoomID = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    log.print_debug(logger, "method_bar_force_exists_room exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    if tmpRoom.isStatePK(): #pk状态不允许强退
        tmpSendMsgUtil.update_res("room_not_admit_exit")
        tmpSendMsgUtil.send(cmd)
        return
    
    tmpA, tmpB = tmpRoom.getRoomUserObjList()
    _deleteRoomProcess(tmpRoom, tmpA, tmpB, "force_exists", tmpOwnerUser.getUID()) #强退
    
    
#-----#续杯结果-------
def method_bar_room_addtime(request, data):  
    socket_id = request.socket_id
    cmd = "bar_room_addtime"

    data_dict = json_decode(data)
    tmpAnswer = data_dict.get('type')               #0:拒绝 1:同意    
    tmpPayType = data_dict.get('pay_type')          #"gold":金币  "money"：比索 
    if tmpPayType is None:
        tmpPayType = "gold"
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return 
        
    tmpRoomID = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
    
    #人数不等于2 或 房间状态不是普通聊天，则房间不允许续杯
    tmpRoomUserList = tmpRoom.getRoomUserObjList()
    if len(tmpRoomUserList) != 2 or tmpRoom.isStatePK(): 
        log.print_warning(logger, "method_bar_room_addtime exec, fail, room:[%s]_not_admit_addtime, sockID:[%s]" 
                          % (tmpRoomID, socket_id)) 
        tmpSendMsgUtil.update_res("room_not_admit_addtime")   
        tmpSendMsgUtil.send(cmd)
        return   
    
    log.print_debug(logger, "method_bar_room_addtime exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
    
    tmpAnswer += 1  #0默认， 1不同意, 2:同意
    tmpRoom.m_addtime_info.setAgree(tmpOwnerUser, tmpAnswer)
    
    if tmpOwnerUser.getSex() == 1:  #男方选择的续杯方式
        tmpRoom.m_addtime_info.setPayType(tmpPayType)
    
    #发送响应消息---
    tmpSendMsgUtil.send(cmd)
    
    #是否双方都提交了续杯
    if not tmpRoom.m_addtime_info.isAllSelect(): 
        log.print_debug(logger, "method_bar_room_addtime exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s========not all answer============="
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data)) 
        return
    
    #关闭续杯结果定时器
    tmpRoom.stopTimerWaitAddTime() 

    tmpA, tmpB = tmpRoomUserList
    addtimeFailType = "addtime_fail"    #续杯失败原因, 一方拒绝续杯
    
    while True:
        if tmpRoom.m_addtime_info.isAllAgree():#双方都同意
            tmpUserBoy = tmpA
            if tmpB.getSex() == 1:
                tmpUserBoy = tmpB
            #---男方数值是否够, 够则扣，不够， 则结束聊天
            tmpLogicMapObj = ConfigManager.getLogicInfo("BarRoom_bar_room_addtime") #获取配置项
            if tmpRoom.m_addtime_info.getPayType() == "money":  #(金币,比索同时只选择其一)
                ConfigManager.setLogicInfoVal_Gold(tmpLogicMapObj, 0)
                addtimeFailType = "addtime_fail_not_money" #续杯失败原因, 男方比索不足
            else:
                ConfigManager.setLogicInfoVal_Money(tmpLogicMapObj, 0)  
                addtimeFailType = "addtime_fail_not_gold"  #续杯失败原因, 男方金币不足
            if not util.CountUserUtil.judgeAndEditExt(cmd, tmpUserBoy.getRequest(), tmpUserBoy.getUID(), tmpLogicMapObj):
                break  #数值扣除不成功, 则返回,结束聊天
                  
            tmpRoom.m_addtime_info.setAddTimeState() #房间设置为已续杯
            
            #给双方发送继续聊天消息---  
            cmd = "bar_room_keep"
            tmpRoom.sendMsgToAll(cmd, tmpSendMsgUtil)
            
            #给房间所有人push状态变化
            tmpRoom.pushRoomUserBarState()
            
            return
        break
    #一方不同意， 则结束聊天
    _deleteRoomProcess(tmpRoom, tmpA, tmpB, addtimeFailType)

#------#聊天房间中, 看相片--
def method_bar_room_see_pic(request, data):     
    socket_id = request.socket_id
    cmd = "bar_room_see_pic"
    
    data_dict = json_decode(data)
    tmpAskUID = data_dict.get('uid')                  #用户ID   

    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return 
        
    tmpRoomID = tmpOwnerUser.getRoomID(); #房间ID
    tmpRoom = tmpBarManager.getRoomExt(cmd, tmpSendMsgUtil, socket_id, tmpRoomID)
    if tmpRoom is None:     #当前房间不存在， 则发错误消息
        return
     
    log.print_debug(logger, "method_bar_room_see_pic exec, room_id:[%s], RoomUsers:%s, socket_id:[%s], data:%s"
                     % (tmpRoomID, tmpRoom.getRoomUserList(), socket_id, data))
        
    if tmpAskUID != tmpOwnerUser.getUID(): #查看别人的信息
        tmpAskUser = UserManager.getUserByUIDExt(cmd, tmpSendMsgUtil, tmpAskUID);     
        if tmpAskUser is None: #目标对象不存在， 则发错误消息
            return 
        
        #判断是否有效道具“望远镜”， 无， 则扣数值
        tmpProps = PropManager.instance().isUsingPropLoupe(tmpOwnerUser)
        if not tmpProps:
            if not util.CountUserUtil.judgeAndEditExt(cmd, tmpOwnerUser.getRequest(), tmpOwnerUser.getUID(), "BarRoom_bar_room_see_pic"):
                return  #数值扣除不成功, 则返回
    
    #发送消息---
    tmpSendMsgUtil.send(cmd)

#------酒吧大厅查看别的用户信息, 扣数值    
def method_bar_get_user_info(request, data):   
    '''此接口只为了扣数值而存在'''  
    socket_id = request.socket_id
    cmd = "bar_get_user_info"
    
    data_dict = json_decode(data)
    tmpReqUID = data_dict.get('uid')                #用户ID   

    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return  
    
    log.print_debug(logger, "method_bar_get_user_info exec, socket_id:[%s], data:%s" % (socket_id, data))

    if tmpReqUID != tmpOwnerUser.getUID():  #查看别人的信息, 需扣数值
        tmpTargetUser = user.UserManager.get_user_by_uid(tmpReqUID)
        if not tmpTargetUser:
            newUserinfo = user.UserManager.get_user_basic_info(tmpReqUID, "sex")    #查询DB数据
            tmpTargetUser = user.User(0, newUserinfo, None)
            
        tmpConfigName = "BarRoom_bar_get_user_info_for_same_sex"    #同性扣数值
        if tmpTargetUser.getSex() != tmpOwnerUser.getSex():         #异性扣数值
            tmpConfigName = "BarRoom_bar_get_user_info_for_diffent_sex" 
            
        if not util.CountUserUtil.judgeAndEditExt(cmd, tmpOwnerUser.getRequest(), tmpOwnerUser.getUID(), tmpConfigName):
            return  #数值扣除不成功, 则返回
    
    #发送消息---
    tmpSendMsgUtil.send(cmd)


#------------------------------------------
#------#进入名人堂--
def method_enter_order_modul(request, data): 
    socket_id = request.socket_id
    log.print_debug(logger, "method_enter_order_modul exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "enter_order_modul"

    tmpSendMsgUtil = util.SendMsgUtil(request)    #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    tmpBarManager = BarOrderManager.instance()       #酒吧管理器
    tmpBarManager.enter(tmpOwnerUser, "bar_order")          #进入名人堂
    
    tmpMyTOrder = tmpBarManager.getOrder(tmpOwnerUser)      #我名人堂的排名
    tmpSendMsgUtil.add_item("order", tmpMyTOrder)           #我的排名
    tmpSendMsgUtil.add_item("single_total", tmpBarManager.getTotalSingleCount())  #单身总数
    tmpSendMsgUtil.add_item("double_total", tmpBarManager.getTotalDoubleCount())  #房间总数 
    #发送消息---
    tmpSendMsgUtil.send(cmd)
    

#------#离开名人堂--
def method_leave_order_modul(request, data): 
    socket_id = request.socket_id
    log.print_debug(logger, "method_leave_order_modul exec, socket_id:[%s], data:%s" % (socket_id, data))  
    cmd = "enter_order_modul"
    
    tmpBarManager = BarOrderManager.instance()      #酒吧名人堂管理对象    
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    tmpBarManager.leaveBarOrder(request, tmpOwnerUser)   #处理离开酒吧/名人堂或者用户掉线

#---获取排名者信息
def _get_order_list(tmpOwnerUser, tmpReqSex, tmpBarManager, tmpSendMsgUtil, tmpReqBegin, tmpReqEnd):    
    tmpList = tmpBarManager.s_map_order_boy_by_order
    if tmpReqSex is None: 	
		tmpReqSex = tmpOwnerUser.getDiffentSex() #默认获取异性排名列表		
    if tmpReqSex == 0:
        tmpList = tmpBarManager.s_map_order_girl_by_order
    
    singleTotal = len(tmpList)  #该性别排队总人数
        
    tempSingleInfo = []
    index = tmpReqBegin
    ownerUID = tmpOwnerUser.getUID()
    
    while index <= tmpReqEnd:
        tmpObj = tmpList.get(index)       #获取某排名的UID {"type":"default", "uid":1111}
        index += 1
        if tmpObj:
            uid = tmpObj.get('uid')
            tmpUser = UserManager.get_user_by_uid(uid)
            if tmpUser is None:
                continue
            tmpItems = tmpBarManager.getUserInfoToClient(tmpUser)    #获取用户信息
            tmpItems["order"] = tmpBarManager.getOrder(tmpUser)     #用户排名信息
            tmpItems["type"] = tmpObj.get('type')                   #"default":一页多人,  "single":一页一人
            tempSingleInfo.append(tmpItems)
            
            tmpUser.insertBarSeeMeList(ownerUID)             #--把 我的uid加入到对方的“看见我的人队列"       
            tmpOwnerUser.insertBarISeeList(tmpUser.getUID()) #--把对方的uid加入到我的“我看见的人队列"
    
    #添加列表信息到发送字典
    tmpSendMsgUtil.add_item("single_total", singleTotal) #该性别排队总人数
    tmpSendMsgUtil.add_item("single", tempSingleInfo)

#----
def _get_order_list_Ext(tmpOwnerUser, tmpReqSex, tmpBarManager, tmpSendMsgUtil, tmpReqBegin, tmpReqEnd):  
    if tmpReqSex is None: 	
        tmpReqSex = tmpOwnerUser.getDiffentSex()#默认获取异性排名列表
    tmpList = tmpBarManager.getSingleUserList(tmpReqSex)
    
    singleTotal = len(tmpList)  #该性别排队总人数
        
    tempSingleInfo = []
    index = tmpReqBegin
    ownerUID = tmpOwnerUser.getUID()
    
    if singleTotal > 0:
        while index <= tmpReqEnd and index < singleTotal:
            tmpUID = tmpList[index]   
            tmpUser = UserManager.get_user_by_uid(tmpUID)     
            index += 1
            if tmpUser is None:
                continue
            tmpItems = tmpBarManager.getUserInfoToClient(tmpUser)    #获取用户信息
            tmpItems["order"] = 0                   #tmpBarManager.getOrder(tmpUser)     #用户排名信息
            tmpItems["type"] = "default"                   #"default":一页多人,  "single":一页一人
            tempSingleInfo.append(tmpItems)
            
            tmpUser.insertBarSeeMeList(ownerUID)             #--把 我的uid加入到对方的“看见我的人队列"       
            tmpOwnerUser.insertBarISeeList(tmpUser.getUID()) #--把对方的uid加入到我的“我看见的人队列"
    
    #添加列表信息到发送字典
    tmpSendMsgUtil.add_item("single_total", singleTotal) #该性别排队总人数
    tmpSendMsgUtil.add_item("single", tempSingleInfo)
    

#-----#获取单身列表(排序)---
def method_get_order_list(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_get_order_list exec, socket_id:[%s], data:%s" % (socket_id, data)) 
    cmd = "get_order_list"    
    
    data_dict = json_decode(data)
    tmpReqSex = data_dict.get('sex')        #性别
    tmpReqBegin = data_dict.get('begin')    #内容
    tmpReqEnd = data_dict.get('end')        #内容

    tmpBarManager = BarOrderManager.instance()      #酒吧管理器
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    #限定请求的数量
    tmpBarOrderMax = const.Config_GetBarOrderMaxCount() #限定请求长度
    tmpLen = tmpReqEnd - tmpReqBegin   #req range
    if tmpLen < 0 or tmpLen > tmpBarOrderMax:
        tmpSendMsgUtil.update_res("bad_request")   
        tmpSendMsgUtil.send(cmd)
        log.print_warning(logger, "method_get_order_list exec, request range error, \
                        0<default_BarOrderMax<%s, req_begin:%s; req_end:%s" % 
                          (tmpBarOrderMax, tmpReqBegin, tmpReqEnd))
        return
    
    #--获取排名者信息
    #_get_order_list(tmpOwnerUser, tmpReqSex, tmpBarManager, tmpSendMsgUtil, tmpReqBegin, tmpReqEnd)
    _get_order_list_Ext(tmpOwnerUser, tmpReqSex, tmpBarManager, tmpSendMsgUtil, tmpReqBegin, tmpReqEnd)
    
    #发送消息---
    tmpSendMsgUtil.send(cmd)

#-----#定位到自己的排名---
def method_location_my_order(request, data):
    socket_id = request.socket_id
    log.print_debug(logger, "method_location_my_order exec, socket_id:[%s] data:%s" % (socket_id, data)) 
    cmd = "location_my_order"

    tmpBarManager = BarOrderManager.instance()      #酒吧管理器
    tmpSendMsgUtil = util.SendMsgUtil(request)      #消息发送器    
    tmpOwnerUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);     
    if tmpOwnerUser is None: #当前用户对象不存在， 则发错误消息
        return
    
    #获取配置数量
    tmpBarOrderFront = const.Config_GetBarOrderLocationCount_Front()  #名人堂定位,获取前面几位
    tmpBarOrderBack = const.Config_GetBarOrderLocationCount_Back()    #名人堂定位,获取后面几位
    
    myOrder = tmpBarManager.getOrder(tmpOwnerUser) #我的排名
    tmpReqBegin = myOrder - tmpBarOrderFront
    tmpReqEnd = myOrder + tmpBarOrderBack
    
    if tmpReqBegin < 0:
        tmpReqBegin = 0
    if tmpReqEnd < 0:
        tmpReqEnd = 0
    
    #--获取排名者信息
    _get_order_list(tmpOwnerUser, tmpOwnerUser.getSex(), tmpBarManager, tmpSendMsgUtil, tmpReqBegin, tmpReqEnd)
    
    #发送消息---
    tmpSendMsgUtil.send(cmd)

#-wudi-2012.03.01#
def method_game_pk(request,data):
    '''pk游戏，找对方PK，对方可以是不在线的用户'''
    cmd = "game_pk"
    socket_id = request.socket_id
    tmpSendMsgUtil = util.SendMsgUtil(request)  #消息发送器    
    data_dict = json_decode(data)    
    tmpUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);
    
    tmpMyUid = tmpUser.getUID()    #我
    tmpToUid = data_dict.get('uid')    #对方

    pkResultList = Room.getPKResult(tmpMyUid, tmpToUid)
    tmpWinnerUid = pkResultList[-1]['winUID']
    if tmpWinnerUid==False:
        tmpSendMsgUtil.update_res("user_is_null")        
        tmpSendMsgUtil.send(cmd)
        return
    
    #第一次PK必须胜利
    tmpTask = tmpUser.m_task
    tmpNewUser = 0    
    for v in tmpTask:
        if v.get('type')=='first':
            tmpNewUser=1
            tmpTaskList = v.get('task')
            for vv in tmpTaskList:
                if vv.get('type')=='first_steal_gold':
                    tmpNewUser=0
            
    if tmpToUid is tmpWinnerUid:  #PK者准入PK失败
        strResult = "lose"
        strConfigName = "game_pk_lose" 
    else: #准入pk胜利
        strResult = "win"
        strConfigName = "game_pk_win"
    if tmpNewUser==1:
        strResult = "win"
        strConfigName = "game_pk_win"
    #---数值变化 , 数值不够, 则返回   
    if not util.CountUserUtil.judgeAndEditExt(cmd, request, tmpMyUid, strConfigName):
        return    
    tmpSendMsgUtil.add_item('is_win', strResult)
    tmpSendMsgUtil.add_item('huihe', pkResultList)
    tmpSendMsgUtil.send(cmd)

def method_get_pker_info(request,data):
    '''获取PK者用户资料'''
    cmd = "get_pker_info"
    data_dict = json_decode(data)
    tmpSendMsgUtil = util.SendMsgUtil(request)  #消息发送器    
    
    tmpToUid = data_dict.get('uid')    #对方       
    sql = "SELECT  a.uid,a.sex, \
    b.nickname, b.charm,b.assets,b.count_atted,b.count_invite,b.my_props_using,b.my_bodyinfo, \
    b.eloquence, b.knowledge, b.constitution, b.mood, b.appearance, \
    c.my_attt FROM t_user a, t_user_data b ,t_user_record c \
    WHERE a.uid = b.uid AND a.uid = c.uid AND a.uid = %d "%tmpToUid
    conn = mysqlHelper.mysql()
    tmpUser = conn.getRow(sql)
    
    if tmpUser:
        _decodeRowItem(tmpUser, 'my_props_using')
        _decodeRowItem(tmpUser, 'my_bodyinfo')        
            
        if tmpUser.get('my_attt'):
            tmpUser['my_friend_size'] = len(json_decode(tmpUser['my_attt']))
        else:
            tmpUser['my_friend_size'] = 0
        del tmpUser['my_attt']    
        tmpSendMsgUtil.add_item('user', tmpUser)
    else:
        tmpSendMsgUtil.update_res("user_is_null")     
    tmpSendMsgUtil.send(cmd)
    

def method_get_game_pk_list(request,data):
    '''获取PK列表,取得当前用户魅力值相近的用户列表，随机发送给客户端'''
    cmd = "get_game_pk_list"
    socket_id = request.socket_id    
    tmpSendMsgUtil = util.SendMsgUtil(request)  #消息发送器    
    tmpUser = UserManager.getUserExt(cmd, tmpSendMsgUtil, socket_id);
    
    if not tmpUser:
        return
    
    tmpUid = tmpUser.getUID()
    
    tmpUidList = get_pk_users(tmpUser,25)
    if len(tmpUidList)<10:
        tmpUidList = get_pk_users(tmpUser,50)
    if len(tmpUidList)<10:
        tmpUidList = get_pk_users(tmpUser,75)
    if len(tmpUidList)<10:
        tmpUidList = get_pk_users(tmpUser,100)
            
    tmpSendMsgUtil.add_item('list', tmpUidList)    
    tmpSendMsgUtil.send(cmd)

def get_pk_users(tmpUser,dem=25):
    tmpUid = tmpUser.getUID()
    sql = "SELECT a.uid FROM t_user_data a ,t_user b WHERE a.uid = b.uid AND a.uid != %d AND a.charm<= %d AND a.charm >= %d AND b.sex = %d LIMIT 25 "%(tmpUid,tmpUser.getCharm(),int(tmpUser.getCharm()-dem),tmpUser.getSex())
    conn = mysqlHelper.mysql()
    tmpAllUid = conn.getAll(sql)
    tmpUidList = []
    if tmpAllUid:
        for v in tmpAllUid:
            tmpUidList.append(v['uid'])            
        
    sql = "SELECT a.uid FROM t_user_data a ,t_user b \
    WHERE a.uid = b.uid AND a.uid != %d AND a.charm < %d AND a.charm> %d  AND b.sex = %d LIMIT 25 "%(tmpUid,int(tmpUser.getCharm()+dem),tmpUser.getCharm(),tmpUser.getSex())
    
    tmpAllUid = conn.getAll(sql)
    if tmpAllUid:
        for v in tmpAllUid:
            tmpUidList.append(v['uid'])   
    if tmpUidList:         
        util.listShuffle(tmpUidList)   
    return tmpUidList

def _decodeRowItem(row, name):
    if row[name]:
            row[name] = json_decode(row[name])
    else:
        row[name] = {}       
    

#------------------------------------------
#----方法注册---------
util.registMethod("enter_bar", method_enter_bar)            #进入酒吧
util.registMethod("leave_bar", method_leave_bar)            #离开酒吧

util.registMethod("get_bar_list", method_get_bar_list)      #获取单身/聊天中列表
util.registMethod("ask_talking", method_ask_talking)        #请求搭讪
util.registMethod("answer_talking", method_answer_talking)  #同意或者拒绝搭讪请求

util.registMethod("send_talking_info", method_send_talking_info)    #发聊天信息 
util.registMethod("send_action", method_send_action)                #发动作
util.registMethod("send_music", method_send_music)                  #点歌

util.registMethod("bar_pk_before", method_bar_pk_before)            #准入PK, 获取房间原配信息
util.registMethod("bar_pk", method_bar_pk)                          #准入PK
util.registMethod("bar_pk_show", method_bar_pk_show)                #准入PK, 通知开始显示第三者形象
util.registMethod("bar_pk_select_user", method_bar_pk_select_user)  #异性同意某人插足

util.registMethod("ask_auto_talking", method_ask_auto_talking)                      #请求自动匹配
util.registMethod("ask_cancel_auto_talking", method_ask_cancel_auto_talking)        #请求取消自动匹配 

util.registMethod("bar_ask_exist_room", method_bar_ask_exist_room)          #请求退出约会
util.registMethod("bar_answer_exists_room", method_bar_answer_exists_room)  #同意或者拒绝退出约会请求
util.registMethod("bar_force_exists_room", method_bar_force_exists_room)    #强退出约会

util.registMethod("bar_room_addtime", method_bar_room_addtime)              #续杯
util.registMethod("bar_room_see_pic", method_bar_room_see_pic)              #聊天房间中, 看相片
util.registMethod("bar_get_user_info", method_bar_get_user_info)            #酒吧大厅查看用户信息

util.registMethod("enter_order_modul", method_enter_order_modul)            #进入名人堂
util.registMethod("leave_order_modul", method_leave_order_modul)            #离开名人堂

util.registMethod("get_order_list", method_get_order_list)                  #获取单身列表(排序)
util.registMethod("location_my_order", method_location_my_order)            #定位到自己的排名

util.registMethod("game_pk", method_game_pk)                                    #PK游戏，找人PK
util.registMethod("get_game_pk_list", method_get_game_pk_list)                  #获取PK列表
util.registMethod("get_pker_info", method_get_pker_info)                        #获取PK者信息
